// ==UserScript==
// @name         生财有术领队后台-船员打卡数据下载
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  获取网站的打卡数据并下载为Excel
// @author       土豆君(tudoujunh)
// @match        https://scys.com/volunteer/operation/activity/user?*
// @grant        none
// @require      https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js
// @updateURL    https://gitee.com/tudoujunha/scys.user.export/raw/master/job.statistics.scys.user.js
// ==/UserScript==

(function() {
    'use strict';

    // 创建下载按钮
    function createDownloadButton() {
        const button = document.createElement('button');
        button.textContent = '导出打卡数据';
        button.className = 'cxd-Button cxd-Button--default cxd-Button--size-default';
        button.style.margin = '10px';
        return button;
    }

    // 添加下载按钮到指定位置
    function addDownloadButton() {
        const targetButton = document.evaluate(
            '//*[@id="app"]/div/div/div/div/div/div[2]/div[2]/div[1]/div[1]/div[2]/div[2]',
            document,
            null,
            XPathResult.FIRST_ORDERED_NODE_TYPE,
            null
        ).singleNodeValue;

        if (targetButton) {
            const downloadButton = createDownloadButton();
            targetButton.parentNode.insertBefore(downloadButton, targetButton.nextSibling);
            return downloadButton;
        } else {
            console.error('未找到目标按钮');
            return null;
        }
    }

    // 等待目标元素加载完成
    function waitForElement(selector, callback, maxTries = 10, interval = 1000) {
        let tries = 0;
        const checkElement = () => {
            const element = document.querySelector(selector);
            if (element) {
                callback(element);
            } else if (tries < maxTries) {
                tries++;
                setTimeout(checkElement, interval);
            } else {
                console.error('未找到目标元素');
            }
        };
        checkElement();
    }

    async function getAllPageData() {
        let allData = [];
        let currentPage = 1;
        let totalPages = getTotalPages();

        // 获取表头
        const headers = getTableHeaders();
        allData.push(headers);

        while (currentPage <= totalPages) {
            const pageData = getTableData();
            allData = allData.concat(pageData);

            if (currentPage < totalPages) {
                await goToNextPage();
                await new Promise(resolve => setTimeout(resolve, 1000)); // 等待页面加载
            }
            currentPage++;
        }

        return allData;
    }

    function getTotalPages() {
        const paginationItems = document.querySelectorAll('.cxd-Pagination-pager-item');
        return parseInt(paginationItems[paginationItems.length - 1].textContent);
    }

    function getTableHeaders() {
        const thead = document.querySelector('#app > div > div > div > div > div > div.cxd-Crud > div.cxd-Table.cxd-Crud-body > div.cxd-Table-contentWrap > div > div.cxd-Table-content.scrollbar-external.scroll-content > table > thead');
        const headerRows = thead.querySelectorAll('tr');

        // 只处理第二行表头
        const headers = Array.from(headerRows[1].querySelectorAll('th')).map(th => {
            const span = th.querySelector('div.cxd-TableCell--title > span.cxd-TplField > span');
            return span ? span.textContent.trim() : '';
        });

        return headers;
    }

    function getTableData() {
        const table = document.querySelector('#app > div > div > div > div > div > div.cxd-Crud > div.cxd-Table.cxd-Crud-body > div.cxd-Table-contentWrap > div > div.cxd-Table-content.scrollbar-external.scroll-content > table > tbody');
        const data = [];

        // 提取表格内容
        table.querySelectorAll('tr').forEach(row => {
            const rowData = Array.from(row.querySelectorAll('td')).map(cell => cell.textContent.trim());
            data.push(rowData);
        });

        return data;
    }

    function goToNextPage() {
        const nextButton = document.querySelector('.cxd-Pagination-next');
        if (nextButton && !nextButton.classList.contains('is-disabled')) {
            nextButton.click();
            return new Promise(resolve => setTimeout(resolve, 1000)); // 等待页面加载
        }
        return Promise.resolve();
    }

    // 等待目标元素加载完成后添加下载按钮
    waitForElement('.cxd-Crud-toolbar', () => {
        const downloadButton = addDownloadButton();
        if (downloadButton) {
            downloadButton.addEventListener('click', async function() {
                const allData = await getAllPageData();

                // 创建工作簿和工作表
                const wb = XLSX.utils.book_new();
                const ws = XLSX.utils.aoa_to_sheet(allData);

                // 将工作表添加到工作簿
                XLSX.utils.book_append_sheet(wb, ws, "船员打卡数据");

                // 生成Excel文件并下载
                XLSX.writeFile(wb, "船员打卡数据.xlsx");
            });
        }
    });
})();